<template>
  <div>
    <div class="gva-search-box">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline" @keyup.enter="onSubmit">
        <el-form-item label="创建时间">
          <el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始时间" />
          —
          <el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束时间" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="openDialog">新增</el-button>
        <el-popover v-model:visible="deleteVisible" placement="top" width="160">
          <p>确定要删除吗？</p>
          <div style="text-align: right; margin-top: 8px;">
            <el-button type="primary" link @click="deleteVisible = false">取消</el-button>
            <el-button type="primary" @click="deleteSelectedRow">确定</el-button>
          </div>
          <template #reference>
            <el-button icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="deleteVisible = true">删除</el-button>
          </template>
        </el-popover>
      </div>

      <el-table
        ref="multipleTable"
        style="width: 100%"
        border
        :header-cell-style="{background:'#a3c6d2',color:'#849ba1'}"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column align="left" label="日期" :show-overflow-tooltip="true">
          <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
        </el-table-column>
        <el-table-column align="left" label="ID" prop="ID" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="数据库名" prop="udsSchemaName" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="表名" prop="udsTbName" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="数据分类" prop="udsTbCategory" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="表注释" prop="udsTbComment" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="表标签" prop="udsTbLabel" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="备注" prop="remarks" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="唯一值列" prop="uniqueCol" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="primary" link icon="edit" class="table-button" @click="updateUdsTbFunc(scope.row)">变更</el-button>
            <el-button type="primary" link icon="delete" @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" title="自定义数据表" class="dialog-large">
      <el-form
        ref="elFormRef"
        class="x-form"
        :model="mdUdsTb"
        label-position="right"
        :rules="rulesTable"
        :inline="true"
      >
        <el-form-item label="选择库名:" prop="udsSchemaName">
          <el-select v-model="mdUdsTb.udsSchemaName">
            <el-option v-for="item in odsDbSchemaList" :key="item.id" :value="item.label" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="表英文名:" prop="udsTbName">
          <el-input v-model="mdUdsTb.udsTbName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="表中文名:" prop="udsTbComment">
          <el-input v-model="mdUdsTb.udsTbComment" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="表标签:" prop="udsTbLabel">
          <el-input v-model="mdUdsTb.udsTbLabel" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="表数据分类:" prop="udsTbCategory">
          <el-input v-model="mdUdsTb.udsTbCategory" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="备注:" prop="remarks">
          <el-input v-model="mdUdsTb.remarks" placeholder="请输入" />
        </el-form-item>
      </el-form>

      <div style="margin: 5px 0px -5px;">
        <el-button type="primary" icon="plus" @click="newField">新增列</el-button>
        <el-button type="success" icon="plus" @click="newXlsx">导入xlsx文件</el-button>
      </div>

      <el-form ref="elFormRefFlds" :model="formFlds" :rules="rulesField">
        <el-table :data="formFlds.fields" class="tb-input">
          <el-table-column align="left" type="index" label="序列" width="60" />
          <el-table-column align="left" prop="colName" label="ID" width="160">
            <template #default="scope">
              <el-form-item :prop="'mdUdsTb.fields.' + scope.$index + '.colName'">
                <el-input v-model="scope.row.ID" :disabled="true" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="left" prop="colName" label="字段名" width="160">
            <template #default="scope">
              <el-form-item :prop="'mdUdsTb.fields.' + scope.$index + '.colName'" :rules="rulesField.colName">
                <el-input v-model="scope.row.colName" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="left" prop="colDataType" label="字段类型" width="160">
            <template #default="scope">
              <el-form-item :prop="'udsFlds.' + scope.$index + '.colType'" :rules="rulesField.colDataType">
                <el-input v-model="scope.row.colDataType" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="left" prop="colComment" label="字段注释" width="160">
            <template #default="scope">
              <el-form-item :prop="'udsFlds.' + scope.$index + '.colComment'" :rules="rulesField.colComment">
                <el-input v-model="scope.row.colComment" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="left" prop="colKey" label="是否主键" width="100">
            <template #default="scope">
              <el-form-item :prop="'udsFlds.' + scope.$index + '.colKey'">
                <el-checkbox v-model="scope.row.colKey" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="left" prop="notNull" label="是否必填" width="100">
            <template #default="scope">
              <el-form-item :prop="'udsFlds.' + scope.$index + '.notNull'">
                <el-checkbox v-model="scope.row.notNull" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="left" prop="notNull" label="是否自增" width="100">
            <template #default="scope">
              <el-form-item :prop="'udsFlds.' + scope.$index + '.autoIncrement'">
                <el-checkbox v-model="scope.row.autoIncrement" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="left" prop="unique" label="是否唯一" width="100">
            <template #default="scope">
              <el-form-item :prop="'udsFlds.' + scope.$index + '.unique'">
                <el-checkbox v-model="scope.row.unique" />
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column align="left" prop="remarks" label="备注">
            <template #default="scope">
              <el-form-item :prop="'mdUdsTb.fields.' + scope.$index + '.colName'">
                <el-input v-model="scope.row.remarks" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="left" label="操作" width="100" fixed="right">
            <template #default="scope">
              <el-popover v-model="scope.row.visible" placement="top">
                <p>确定删除吗？</p>
                <div style="text-align: right; margin-top: 8px;">
                  <el-button type="primary" link @click="scope.row.visible = false">取消</el-button>
                  <el-button type="primary" @click="deleteField(scope.$index)">确定</el-button>
                </div>
                <template #reference>
                  <el-button type="primary" link icon="delete" @click="scope.row.visible = true">删除</el-button>
                </template>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="enterDialog">保 存</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogExcelVisible" :before-close="closeExcelDialog" title="导入excel模板" class="dialog-mid">
      <div>
        <el-upload
          :action="`${path}/fileUploadAndDownload/upload`"
          :before-upload="checkFile"
          :headers="{ 'x-token': userStore.token }"
          :on-error="uploadError"
          :on-success="uploadSuccess"
          :show-file-list="false"
          class="upload-btn"
        >
          <el-button type="primary">选择文件</el-button><a> {{ uploadedFileNameType }}</a>
        </el-upload>

        <el-table :data="uploadedFlds" class="tb-input">
          <el-table-column align="left" prop="colName" label="字段名" width="160"/>
          <el-table-column align="left" prop="colDataType" label="字段类型" width="160"/>
          <el-table-column align="left" prop="colComment" label="字段注释" width="160"/>
          <el-table-column align="left" prop="colKey" label="是否主键" width="100"/>
          <el-table-column align="left" prop="notNull" label="是否必填" width="100"/>
          <el-table-column align="left" prop="notNull" label="是否自增" width="100"/>
          <el-table-column align="left" prop="unique" label="是否唯一" width="100"/>
          <el-table-column align="left" prop="remarks" label="备注"/>
        </el-table>

      </div>
      <template #footer>
        <div style="padding-bottom: 20px">
          <el-button style="float: right" type="primary" @click="enterExcelDialog">应 用</el-button>
          <el-button style="float: right" @click="closeExcelDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'UdsTb'
}
</script>

<script setup>
import {
  createUdsTb,
  deleteUdsTb,
  deleteUdsTbByIds,
  updateUdsTb,
  findUdsTb,
  getUdsTbList,
} from '@/api/udsTb'

import { formatDate } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, onMounted } from 'vue'
import { getDict } from '@/utils/dictionary'
import { mdUdsTb, formFlds, typeOptions, newField, deleteField, moveUpField, moveDownField } from '@/view/uds/udsTb/udsTb'
import { useUserStore } from '@/pinia/modules/user'

const rulesTable = reactive({
  udsSchemaName: [
    {
      required: true,
      message: '请选择数据库类型',
      trigger: 'blur'
    }
  ],
  udsTbName: [
    {
      required: true,
      message: '表英文名必填',
      trigger: 'blur'
    }
  ],
  udsTbComment: [
    {
      required: true,
      message: '表中文名必填',
      trigger: 'blur'
    }
  ]
})
const rulesField = reactive({
  colName: [
    {
      required: true,
      message: '',
      trigger: 'blur'
    }
  ],
  colComment: [
    {
      required: true,
      message: '',
      trigger: 'blur'
    }
  ],
  colDataType: [
    {
      required: true,
      message: '',
      trigger: 'blur'
    }
  ],
})

const elFormRef = ref()
const elFormRefFlds = ref()

const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

const onSubmit = () => {
  page.value = 1
  pageSize.value = 10
  getTableData()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const getTableData = async() => {
  const table = await getUdsTbList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()


const setOptions = async() => {
}

setOptions()

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteUdsTbFunc(row)
  })
}

const deleteVisible = ref(false)

const deleteSelectedRow = async() => {
  const ids = []
  if (multipleSelection.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据'
    })
    return
  }
  multipleSelection.value &&
  multipleSelection.value.map(item => {
    ids.push(item.ID)
  })
  const res = await deleteUdsTbByIds({ ids })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === ids.length && page.value > 1) {
      page.value--
    }
    deleteVisible.value = false
    await getTableData()
  }
}

const type = ref('')

const updateUdsTbFunc = async(row) => {
  const res = await findUdsTb({ ID: row.ID })
  type.value = 'update'
  if (res.code === 0) {
    mdUdsTb.value = res.data.reudsTb
    formFlds.value.fields = mdUdsTb.value.udsFlds
    dialogFormVisible.value = true
  }
}

const deleteUdsTbFunc = async(row) => {
  const res = await deleteUdsTb({ ID: row.ID })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    await getTableData()
  }
}

const dialogFormVisible = ref(false)

const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
  mdUdsTb.value = {}
}

const closeDialog = () => {
  dialogFormVisible.value = false
  mdUdsTb.value = {
    udsSchemaName: '',
    udsTbName: '',
    udsTbComment: '',
    udsTbLabel: '',
    udsTbCategory: '',
    remarks: '',
  }
}

const enterDialog = async() => {
  elFormRef.value?.validate(async(valid) => {
    if (!valid) {
      return
    }
    mdUdsTb.value.udsFlds = formFlds.value.fields
    let res
    switch (type.value) {
      case 'create':
        res = await createUdsTb(mdUdsTb.value)
        break
      case 'update':
        res = await updateUdsTb(mdUdsTb.value)
        break
      default:
        res = await createUdsTb(mdUdsTb.value)
        break
    }
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialog()
      await getTableData()
    }
  })
}
const emit = defineEmits(['on-success'])
const path = ref(import.meta.env.VITE_BASE_API)
const userStore = useUserStore()
const fullscreenLoading = ref(false)
const uploadedFileNameType = ref('')
const uploadedFlds = ref([])

const checkFile = (file) => {
  fullscreenLoading.value = true
  const isCSV = file.type === 'text/csv'
  const isXLS = file.type === 'application/vnd.ms-excel'
  const isXLSX = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  if (!isCSV && !isXLS && !isXLSX) {
    ElMessage.error('上传文件只能是 csv/xls/xlsx 格式!')
    fullscreenLoading.value = false
  }
  return (isCSV || isXLS || isXLSX)
}
const uploadSuccess = (res) => {
  const { data } = res
  if (data.file) {
    uploadedFileNameType.value = data.file.name
    emit('on-success', data.file.url)
  }
  uploadedFlds.value = res.data.flds
}
const uploadError = () => {
  ElMessage({
    type: 'error',
    message: '上传失败'
  })
  fullscreenLoading.value = false
}
const dialogExcelVisible = ref(false)
const newXlsx = () => {
  dialogExcelVisible.value = true
}
const closeExcelDialog = () => {
  dialogExcelVisible.value = false
  uploadedFlds.value = []
}
const enterExcelDialog = async() => {
  formFlds.value.fields = uploadedFlds.value
  closeExcelDialog()
}
const dialogDbTbVisible = ref(false)
const newDbTb = () => {
  dialogExcelVisible.value = true
}
const closeDbTbDialog = () => {
  dialogDbTbVisible.value = false
  uploadedFlds.value = []
}
const enterDbTblDialog = async() => {
  closeDbTbDialog()
}
const odsDbSchemaList = ref([])
const init = async() => {
  odsDbSchemaList.value = await getDict('odsSchemaList')
}
onMounted(async() => {
  await init()
})

</script>

<style lang="scss" scoped>
.tb-input {
  .el-input {
    margin-left: -10px;
    width: 115%;
    border: 0 !important;
  }

  .el-select {
    margin-left: -10px;
    width: 115%;
  }
}

</style>
